package com.CMS.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import com.CMS.client.TemplateService;
import com.CMS.server.dao.PageDao;
import com.CMS.server.domain.Page;
import com.CMS.shared.HorizontalTemplate;
import com.CMS.shared.Template;
import com.CMS.shared.VerticalTemplate;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class RpcTemplate extends RemoteServiceServlet implements TemplateService
{

	private static final long serialVersionUID = -5809661079735095344L;

    @Override
	public String getStyleSheets(String filePath) 
	{
    	String style=null;
    	
    	File file = new File(filePath);
    		
    	if(file.exists())
    	{	
    		try {
    		    BufferedReader in = new BufferedReader(new FileReader(file));
    		    String str;
    		    style=in.readLine();
    		    while ((str = in.readLine()) != null) {
    		       style += str + "\n";
    		    }
    		    in.close();
    		} catch (IOException e) {
    		}

    	}	    	
		return style;
			
     }
    
    
    @Override
	public void setStyleSheets(String filePath,String styles) 	
	{
    	File file = new File(filePath);
    	
        //creo directorio donde voy a guardar los html
    	//String dir=filePath + "es";
    	//File directorio=new File(dir);
    	//directorio.mkdir();    	
    	if(file.exists())
    	{	
    	   try {
    			
    			BufferedWriter in = new BufferedWriter(new FileWriter(file));
    		    in.write(styles);
    		    in.close();
    		} catch (IOException e) {
    		}

        }	    	
			
     }


	@Override
	public void generatePageFile(String name, String content) {
		File file = new File("..\\war\\Templates\\"+name);
		try {
			
			BufferedWriter in = new BufferedWriter(new FileWriter(file));
		    in.write(content);
		    in.close();
		} catch (IOException e) { }
	}


	@Override
	public void generatePageFile(List<Long> pages, int template) {
		PageDao dao = new PageDao();
		for(int i=0; i<pages.size(); i++){
			Page p = dao.getEntity(pages.get(i));
			
			Template t;
			if(template == 1)
				t = new HorizontalTemplate();
			else
				t = new VerticalTemplate();
			
			t.setContent(p.getLastVersion().getContent());
			
			String filePath = "..\\war\\Templates\\";
			String dir = filePath + p.getLang().getDescription().substring(0,2);
	    	File directorio = new File(dir);
	    	directorio.mkdir();
	    	File file = new File(dir+"\\"+p.getName());
	    	try{
	    		BufferedWriter in = new BufferedWriter(new FileWriter(file));
			    in.write(t.getPage());
			    in.close();
	    	}catch (IOException e) { }
		}
	}
}   
